package com.iot.controller;


import com.iot.domain.Album;
import com.iot.domain.AlbumVo;
import com.iot.service.FastDfsService;
import com.iot.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;

/*相册的控制器*/
@Controller
public class AlbumController {


    @Autowired
    private FastDfsService fastDfsService;
    @Autowired
    private RedisService redisService;

    /*创建相册*/
    @RequestMapping("/createAlbum")
    public
    String createAblum(MultipartHttpServletRequest request, Album album) throws  Exception {

        System.out.println(album);
        String contextPath = request.getContextPath();
        System.out.println(contextPath);
        //判断相册的名字是否存在
        if (redisService.existAlbum(album.getName())){
            return  "the AlbumName is exist Please try again";
        }

        //获取请求的文件
        List<MultipartFile> albumCover = request.getFiles("AlbumCover");


        //将文件写入磁盘并且保存到对应的相册中
        fastDfsService.uploadFile(album, albumCover);
        //跳转相册的页面
        return "showAlbum";

    }



    /*找到所有的相册*/
    @RequestMapping("/getAlbums")
    public  ModelAndView getAlbums(){

        ModelAndView modelAndView=new ModelAndView();
        try {
            List<AlbumVo> allAlbum = redisService.findAllAlbum();
            //找到所有的相册
            if (allAlbum!=null){

                modelAndView.addObject("albums",allAlbum);
                modelAndView.setViewName("showAlbum");
            return  modelAndView;
            }else {
                modelAndView.setViewName("showAlbum");
            }
        return modelAndView;

        } catch (IOException e) {
            e.printStackTrace();
        }
        return modelAndView;

    }



    /*点击对应的相册  加载出相册对应的照片*/
    @RequestMapping("/showPicture")
    public  ModelAndView showAlbum(String albumName) throws IOException {
        //通过相册名获取相册中的照片
        String newalbumName=new String(albumName.getBytes("ISO8859-1"),"UTF-8");
        Album album = redisService.findPictureByAlbumName(newalbumName);
        System.out.println(albumName);
        System.out.println(album);
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.setViewName("showPictures");
       /* modelAndView.setViewName("guanghui");*/

        modelAndView.addObject("pictures",album.getPictures());

        return  modelAndView;

    }

}